function broadcast (componentName, eventName, params) {
  this.$children.forEach(child => {
    const name = child.$options.name

    if (name === componentName) {
      child.$emit.apply(child, [eventName].concat(params))
    } else {
      // todo 如果 params 是空数组，接收到的会是 undefined
      broadcast.apply(child, [componentName, eventName].concat([params]))
    }
  })
}

export default {
  methods: {
    /*
    * 查找最近的具有model的组件（FormGroup或者DynamicForm）
    * */
    findNMCParent () {
      let parent = this.$parent || this.$root
      let name = (parent && parent.$options.name) || ''
      while (parent && (!name || (name !== 'DynamicFormFormGroup' && name !== 'DynamicForm'))) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.name
        }
      }
      if (parent && (name === 'DynamicFormFormGroup' || name === 'DynamicForm')) {
        return parent
      }
      return null
    },

    /*
    * 获取DynamicForm组件
    * */
    getDynamicForm () {
      let parent = this.$parent || this.$root
      let name = (parent && parent.$options.name) || ''
      while (parent && (!name || name !== 'DynamicForm')) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.name
        }
      }
      if (parent && (name === 'DynamicForm')) {
        return parent
      }
      return null
    },

    /*
    * componentNames 只要命中其中一个组件即成功
    * */
    dispatch (componentNames, eventName, params) {
      let last = this
      let parent = this.$parent || this.$root
      let name = parent.$options.name

      while (parent && (!name || componentNames.indexOf(name) === -1)) {
        last = parent
        parent = parent.$parent

        if (parent) {
          name = parent.$options.name
        }
      }
      if (parent && componentNames.indexOf(name) > -1) {
        parent.$emit.apply(last, [eventName].concat(params))
      }
    },

    broadcast (componentName, eventName, params) {
      broadcast.call(this, componentName, eventName, params)
    }
  }
}
